//
//  ViewController.m
//  LCWebViewDemo
//
//  Created by lcc on 16/8/22.
//  Copyright © 2016年 early bird international. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>
#import "promotionTVC.h"

#import "../Utils/DataPersist.h"

#import "../MKConstant.h"
#import "../network.h"


#import "../aboutUs/UIScrollView的快速使用-Bridging-Header.h"
#import "UIScrollView的快速使用-Swift.h"

#import "Constants.h"


#import "promotionTVCell2.h"
#import "contactTVC2.h"

#import "promotionTVCell3.h"

@interface promotionTVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSData *itemHTMLData;
    NSString *pagetitle;
    
    UIActivityIndicatorView *loadActivity;  //加载动画
    UIView *activityBg;
    
    contactTVC2 *contvc2;
}

@property (nonatomic,retain) UIWebView *webView;
@property (nonatomic,retain) UITableView *tableView;


@end

@implementation promotionTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 颜色
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor whiteColor];
    //NSString *title = self.itemDatasource.title;
    //NSString *title = @"1";
    //NSString *title = self.itemDatasource;
    //self.navigationItem.title = title;  //设置navigationItem.title 标题
    [self.navigationController.navigationBar setTitleTextAttributes:@{
                                                                      NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor grayColor]                }];
    
    //网络初始化
    //等网络请求 通知后再加载数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setitemdata) name:@"getitemDataNOTIF" object:nil];
    
    network *getdata = [[network alloc]init];
    
    //NSLog(@" promotionTVC  promotionid %@",self.itemDatasource);
    [getdata itemVcgetJsonData:@"promotionid" item:self.itemDatasource];  //获取子页面数据 self.itemDatasource
    [self loadingView];  //等待网络结果动画
    
    //NSMutableArray *itemArray = [self plugInfoJson];
    //NSLog(@"itemArray %@ ",itemArray);
    
    //接收提交信息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notifAction:) name:@"Promotionsend" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PromotionmailAction:) name:@"Promotionmail" object:nil];
    //[self setitemdata];
    //[self creatView];

}

- (void)creatView{
    
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    //[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
    
    //    // 将请求到的网页数据用loadHTMLString 的方法加载
    NSString *htmlStr = [[NSString alloc] initWithData:itemHTMLData encoding:NSUTF8StringEncoding];
    
    NSURL *baseUrl = [NSURL URLWithString:@"file:///assets/"];
    //[self.webView loadHTMLString:[self.viewModel getHtmlString] baseURL:baseUrl];
    [self.webView loadHTMLString:htmlStr baseURL:baseUrl];
    
    //使用kvo为webView添加监听，监听webView的内容高度
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 80;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //去掉tableView行分割线
    
    //设置webView为tableView的header
    self.tableView.tableHeaderView = self.webView;
    
    [self.view addSubview:self.tableView];
    [self bookingview]; //立刻预约页面
}

//实时改变webView的控件高度，使其高度跟内容高度一致
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"contentSize"]) {
        CGRect frame = self.webView.frame;
        frame.size.height = self.webView.scrollView.contentSize.height;
        self.webView.frame = frame;
        
        self.tableView.tableHeaderView = self.webView;
    }
}


#pragma -mark- tableView的代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        /**
         *  表格cell
         */
    
        NSString *image = @"191550736323_.pic_hd.jpg";//[dataSource objectAtIndex:indexPath.row];
          //promotionTVCell *cell = [promotionTVCell createCellWithTableView:tableView];
        //promotionTVCell2 *cell = [promotionTVCell2 createCellWithTableView:tableView];
        promotionTVCell3 *cell = [promotionTVCell3 createCellWithTableView:tableView];
        NSString *protitle = PROTITLE; //常量定义
        
        NSMutableDictionary *protitledic = [[NSMutableDictionary alloc]init];
        [protitledic setValue:@"姓名*" forKey:@"Prolabel1"];
        [protitledic setValue:@"手提電話*" forKey:@"Prolabel2"];
        [protitledic setValue:@"性別*" forKey:@"Prolabel3"];
        [protitledic setValue:@"電郵*" forKey:@"Prolabel4"];
        [protitledic setValue:@"提交" forKey:@"submit"];
        
        [cell loadData:image label:protitle andprotitledic:protitledic];
        return cell;
    }else{
        /**
         *  文字cell
         */
        static NSString *cellID = @"reuseCell";
        UITableViewCell *tableViewCell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (tableViewCell == nil) {
            tableViewCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        tableViewCell.textLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        
        return tableViewCell;
    }
    
    
    
    
}

// cell 指定的高度为300
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     if (indexPath.row == 0) {
         return 370 ;
     }else{
       return 50 ;
     }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)setitemdata{
    //读取数组值
    NSMutableArray *itemArray = [[DataPersist readValueNSMutableArray:@"itemData"] mutableCopy];
    //NSLog(@"itemArray %@ ",itemArray);
    
    NSDictionary *itemdata = [itemArray valueForKey:@"data"];
    //NSLog(@"itemdata is %@",itemdata);
    
    pagetitle = [itemdata valueForKey:@"title"]; //y页面title
    //NSLog(@"pagetitle is %@",pagetitle);
    
    NSString *top_desc = [itemdata valueForKey:@"top_desc"];
    //NSLog(@"banner is %@",banner);
    
    NSString *middle_desc = [itemdata valueForKey:@"middle_desc"];
    //NSLog(@"post_content is %@",post_content);
    
    NSMutableString *headHTML = [NSMutableString string];  //加载本地CSS js
    [headHTML appendString:@"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">"];
    [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"style" withExtension:@"css"]];
    
    [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"w3" withExtension:@"css"]];
    
    [headHTML appendString:@"</head><body>"];
    
    
    NSString *banner = [headHTML stringByAppendingString:top_desc]; //合并banner 和 post_content
    
    
    NSString *midheader = @"<div class='contentcontainer w3-padding-top '><div class='w3-card-2 w3-padding w3-white  w3-row'>";
    NSString *midfooter = @"</div></div>";
    NSString *midHTML = [NSString stringWithFormat:@"%@%@%@",midheader,middle_desc,midfooter];
    
    NSString *str2 = [banner stringByAppendingString:midHTML]; //合并banner 和 post_content
    //NSLog(@"str2 is %@",str2);

    itemHTMLData = [str2 dataUsingEncoding:NSUTF8StringEncoding];
    
  [self creatView];
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    //UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    [self.view addSubview:activityBg];
    
    //UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
    //     //网络请求 延迟时间
    //    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
    //    // 延迟方法
    //    // 1 delayTime 2 thread 3 代码
    //    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //        [loadActivity stopAnimating];
    //        [activityBg removeFromSuperview];
    //        [self dismissViewControllerAnimated:true completion:nil];
    ////        [self setindexdata]; //设置首页数据
    ////        [self setMenuData];
    ////        [self settableView];
    //    });
    
}
-(void)stoploading{
    //加载成功
    [loadActivity stopAnimating];
    [activityBg removeFromSuperview];
}


/// textFiled键盘遮盖
-(void)viewWillAppear:(BOOL)animated
{
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // 销毁通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getitemDataNOTIF" object:nil];
}
- (void)registerForKeyboardNotifications {
    NSLog(@"registerForKeyboardNotifications");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification {
    NSLog(@"keyboardWillShow");
    NSDictionary* info = [aNotification userInfo];
    // 注意不要用UIKeyboardFrameBeginUserInfoKey，第三方键盘可能会存在高度不准，相差40高度的问题
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    // 修改滚动条和tableView的contentInset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
    
    // 跳转到当前点击的输入框所在的cell
    [UIView animateWithDuration:0.2 animations:^{
       // [self.tableView scrollToRowAtIndexPath:_indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        NSIndexPath *tbip = 0;//0; //现在为固定值，找办法修改
     [self.tableView scrollToRowAtIndexPath:tbip atScrollPosition:UITableViewScrollPositionTop animated:NO];
       // NSLog(@"animateWithDuration");
       //self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            
     
    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
    NSLog(@"keyboardWillBeHidden");
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

/////

////接收提交信息
-(void)notifAction:(NSNotification*)notif{
    NSDictionary *dic = notif.userInfo;
//    NSLog(@"s接受到的 字典。%@",dic);
//    NSString *string = [dic valueForKey:@"name"]; //pagetitle
//    NSLog(@"%@",string);
    [self submitAction:dic];
}
-(void)showAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)submitAction:(NSDictionary*)dic{
   

    NSString *username = [dic valueForKey:@"name"]; //pagetitle
    NSString *userphone = [dic valueForKey:@"phone"]; //pagetitle
    NSString *useremail = [dic valueForKey:@"email"]; //pagetitle
    NSString *usersex = [dic valueForKey:@"sex"]; //pagetitle
    
    //NSLog(@"%@",string);
    username = [username stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    userphone = [userphone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    
    // 正则
    if ([username containsString:@"#"] || [username containsString:@"$" ] || [username containsString:@"%"]) {
        [self showAlert:@"警告！" message: @"包含非法字符！"];
    }else if (userphone.length<6){
        NSLog(@"userphone %@",userphone);
        [self showAlert:@"警告！" message: @"電話號碼长度不够！"];
    }else{
        [self loadingView];
        
        
        NSMutableDictionary *senddic = [[NSMutableDictionary alloc]init];
        [senddic setValue:username forKey:@"username"];
        [senddic setValue:userphone forKey:@"userphone"];
        [senddic setValue:useremail forKey:@"useremail"];
        [senddic setValue:usersex forKey:@"usersex"];
        [senddic setValue:self->pagetitle forKey:@"title"];
        
        
        //[self showAlert:@"发送消息" message: @"发送消息成功"];
        network *sendNetWork = [[network alloc]init];
        
        
        [sendNetWork POSTrequest:YOUNGURL type:@"Promotion" senddic:senddic savekey:@"Promotion"];  //发送数据
     
    }
    
}

-(void)PromotionmailAction:(NSNotification*)notif{
    
    NSNumber *num = notif.object;
    int num2 = num.intValue;
    
        dispatch_queue_t q2 = dispatch_get_main_queue();  //get 主线程
        //    2 add Queue
        dispatch_async(q2, ^{
            [self stoploading];
            NSLog(@"currentThread %@ ",[NSThread currentThread]);
            if (num2 == 1) {
                [self showAlert:@"消息" message: @"發送成功"];
            }else{
                [self showAlert:@"消息" message: @"發送失敗"];
            }
        });

   
}

#pragma 立刻预约页面
-(void)bookingview{
    // 5 弹出框 100=40 + 60
    UIView *loginView2 = [[UIView alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH - 40, (UISCREEN_HEIGHT-140)/2, UISCREEN_WIDTH, 140)];
    loginView2.backgroundColor = [UIColor clearColor];
    UIButton *bt_login2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 140)];
    ////  圆角效果
    loginView2.layer.cornerRadius = 2;
    //[bt_login2 setTitle:@"--换种方式--" forState:UIControlStateNormal];
    
    //[bt_login2 setTitleColor:[UIColor colorWithRed:50/255.0 green:189/255.0 blue:170/255.0 alpha:1.0] forState:UIControlStateNormal];
    [bt_login2 addTarget:self action:@selector(applyAction1) forControlEvents:UIControlEventTouchUpInside];
    [bt_login2 setBackgroundImage:[UIImage imageNamed:@"book_40x140.png"] forState:UIControlStateNormal]; //customer_service_50x150
    [loginView2 addSubview:bt_login2];
    
    //    UIImageView *applyImg = [[UIImageView alloc]initWithFrame:CGRectMake((UISCREEN_WIDTH-40-40-20)/2, 50, 40, 40)];
    //    applyImg.image = [UIImage imageNamed:@"customer_service_50x150.png"];
    //    [bt_login2 addTarget:self action:@selector(applyAction2) forControlEvents:UIControlEventTouchUpInside];
    //    [loginView2 addSubview:applyImg];
    
    [self.view addSubview:loginView2];
    
}



-(void)applyAction1{
    if (contvc2 == nil) {
        contvc2 = [[contactTVC2 alloc]init];
    }
    [contvc2 setMenutype:1];  //设置联系我们类型，单一状态
    //[self presentViewController:vc_aboutUSswift animated:YES completion:nil];  //推一个子视图覆盖
    [self.navigationController pushViewController:contvc2 animated:YES];   //同一个navigationController。推出子视图
}


-(void)dealloc{
    
    //销毁的时候别忘移除监听
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    //接受信息 广播
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"Promotionsend" object:nil];
    
    //接受信息 广播 发送成功信息
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"Promotionmail" object:nil];
}


@end
